import { UserLoginReq, UserRegisterReq } from '@/types/request';
import { UserLoginResp, UserRegisterResp, ApiResp } from '@/types/response';
import { UserProfile } from '@/types/user';
import { apiClient, storageService } from '.';



// 用户服务
export const userService = {
  // 用户注册
  register: async (userData: UserRegisterReq): Promise<UserRegisterResp> => {
    try {
      const response = await apiClient.post<UserRegisterResp>('/user/register', userData);
      return response.data;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return error.response.data;
      }
      return { code: 9999, message: '网络请求失败，请稍后重试' };
    }
  },

  // 用户登录
  login: async (credentials: UserLoginReq): Promise<UserLoginResp> => {
    try {
      const response = await apiClient.post<UserLoginResp>('/user/login', credentials);
      
      // 登录成功，存储token和用户信息
      if (response.data.code === 0 && 'data' in response.data) {
        const { token, user } = response.data.data;
        storageService.setToken(token);
        storageService.setUser(user);
      }
      
      return response.data;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return error.response.data;
      }
      return { code: 9999, message: '网络请求失败，请稍后重试' };
    }
  },

  // 获取当前用户信息
  getCurrentUser: async (): Promise<ApiResp<UserProfile>> => {
    try {
      const response = await apiClient.get<ApiResp<UserProfile>>('/user/me');
      return response.data;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return error.response.data;
      }
      return { code: 9999, message: '网络请求失败，请稍后重试' };
    }
  },

  // 退出登录
  logout: () => {
    storageService.clearAuth();
  }
};

// 导出类型定义

